﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Security.Cryptography;
using System.IO;
using System.Text;

using CE.Image;
using CE.User;
using CE.Mail;
using CE.Global;

public partial class user_change_password : MyLanguageBasePage
{
    protected override void InitializeCulture()
    {
        String selectedCulture = CE.Global.General.SetCulture();
        base.InitializeCulture();
    }

    string _redirectUrl = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.General.ChangePassword;
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Customer))
            {
                _redirectUrl = CE.Global.General.GetUrl("/car-insurance/car-details", Page);
                Response.Redirect(_redirectUrl);
            }
        }
        else
        {
            //_redirectUrl = CE.Global.General.GetUrl("/car-insurance/sign-in", Page);
            _redirectUrl = CE.Global.General.GetUrl("/car-insurance/car-details", Page);
            Response.Redirect(_redirectUrl);
        }

        if (Session["ImageCount"] != null)
        {
            if (Convert.ToInt32(Session["ImageCount"].ToString()) > 15)
            {
                lblMessage.Text = Resources.UserMessage.SessionLocked;//"Please try after a few moment! You are session has been locked!";
                btnSubmit.Enabled = false;
                btnNewImage.Enabled = false;
                txtOldPassword.Enabled = false;
                txtSecurityCode.Enabled = false;
            }
            else
            {
                lblMessage.Text = "";
                btnSubmit.Enabled = true;
                btnNewImage.Enabled = true;
                txtOldPassword.Enabled = true;
                txtSecurityCode.Enabled = true;
            }
        }

        if (!Page.IsPostBack)
        {
            Session["UMMSG"] = null;
            if (Session["ImageCount"] != null)
            {
                if (Convert.ToInt32(Session["ImageCount"].ToString()) <= 15)
                {
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                CreateUpdateImageAndSession();
            }
            txtOldPassword.Attributes.Add("onblur", "ShowValidationEffect('" + txtOldPassword.ClientID + "','" + rfvOldPassword.ClientID + "');");
            txtNewPassword.Attributes.Add("onblur", "ShowValidationEffect('" + txtNewPassword.ClientID + "','" + rfvNewPassword.ClientID + "');");
            txtConfirmPassword.Attributes.Add("onblur", "ShowValidationEffect('" + txtConfirmPassword.ClientID + "','" + rfvConfirmPassword.ClientID + "');");
            txtSecurityCode.Attributes.Add("onblur", "ShowValidationEffect('" + txtSecurityCode.ClientID + "','" + rfvSecurityCheck.ClientID + "');");
            LogUserViewedHistory();
        }
    }

    private void LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogViewedHistory("USR", Request, "User change password.");
    }

    private void CreateUpdateImageAndSession()
    {
        MyImage myimage = new MyImage();
        string salt = "";

        if (Session[CE.Global.General.SecurityCheckWord] != null)
        {
            salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
        }
        else
        {
            if (Session[CE.Global.General.SecurityCheckWord] != null)
            {
                salt = myimage.GetRandomWord(Session[CE.Global.General.SecurityCheckWord].ToString());
            }
            else
            {
                salt = myimage.GetRandomWord("all");
            }
        }

        Session[CE.Global.General.SecurityCheckWord] = salt;
        imgCAPTCHA.ImageUrl = @"/CAPTCHA/CAPTCHAImageHandler.ashx?id=" + CE.Security.MySecurity.Encrypt(salt, true);
        txtSecurityCode.Text = "";
    }

    protected void btnNewImage_Click(object sender, EventArgs e)
    {
        CreateUpdateImageAndSession();
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ChangeValidationEffectServerSide("customer");
        Page.Validate("customer");
        if (Page.IsValid)
        {
            if (Session[General.SecurityCheckWord] != null)
            {
                string _usrText = txtSecurityCode.Text.ToUpper();
                string _imgText = Session[CE.Global.General.SecurityCheckWord].ToString().ToUpper();
                if (_usrText == _imgText)
                {
                    AccountDB _accountdb = new AccountDB();
                    Account _account = _accountdb.CheckEmail(Session[CE.Global.General.UserEmail].ToString(), Convert.ToInt32(CE.Global.CEUserType.Customer));
                    if (_account != null)
                    {
                        string _oldPassword = txtOldPassword.Text;
                        string _newPassword = txtNewPassword.Text;
                        if (_account.AuthCode == _oldPassword)
                        {
                            _account.AuthCode = _newPassword;
                            if (_accountdb.Insert(_account) > 0)
                            {
                                _redirectUrl = CE.Global.General.GetUrl("/user/user-message", Page);
                                Session["UMMSG"] = "UMG,1991";
                                Response.Redirect(_redirectUrl);
                            }
                            else
                            {

                                lblMessage.Text = Resources.UserMessage.PasswordChangeFailed;//"Change password failed!Try again later!";
                                CreateUpdateImageAndSession();
                            }
                        }
                        else
                        {
                            lblMessage.Text = Resources.UserMessage.OldasswordWrong;//"Old password is wrong.";
                            CreateUpdateImageAndSession();
                        }
                    }
                    else
                    {
                        lblMessage.Text = Resources.UserMessage.NoEmailFound;//"No such email found.!";
                        CreateUpdateImageAndSession();
                    }
                }
                else
                {
                    lblMessage.Text = Resources.UserMessage.WrongSecurityCheck;//"Wrong security check!";
                    CreateUpdateImageAndSession();
                }
            }
            else
            {
                lblMessage.Text = Resources.UserMessage.SecurityCheckFaild;// "Security Check code was expired. Please try again.";
                CreateUpdateImageAndSession();
            }
        }
    }

    protected void CheckPasswordLength(object source, ServerValidateEventArgs args)
    {
        try
        {
            // Test whether the lenght of value is < 7 or Is Number Value.
            string valArgs = args.Value;
            if (valArgs.IndexOf(' ') != -1 || valArgs.IndexOf('\'') != -1 ||
                valArgs.IndexOf('\"') != -1 || valArgs.IndexOf('~') != -1)
            {
                ((CustomValidator)source).ErrorMessage = "Password include invalid character or space!";
                ((CustomValidator)source).Text = "Password include invalid character or space!";
                args.IsValid = false;
            }
            else if (args.Value.Trim().Length < 6)
            {
                ((CustomValidator)source).ErrorMessage = "Password length should be at 6!";
                ((CustomValidator)source).Text = "Password length should be at 6!";
                args.IsValid = false;
            }
            else if (args.Value.Trim().Length > 20)
            {
                ((CustomValidator)source).ErrorMessage = "Password length should not be over 20!";
                ((CustomValidator)source).Text = "Password length should not be over 20!";
                args.IsValid = false;
            }
            else
            {
                args.IsValid = true;
            }
        }
        catch (Exception ex)
        {
            args.IsValid = false;
        }
    }

    public string CreateSalt(int size)
    {
        RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
        Byte[] buff = new Byte[size];
        rng.GetBytes(buff);

        return Convert.ToBase64String(buff);
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        txtOldPassword.Text = HttpUtility.HtmlEncode(txtOldPassword.Text);
        txtNewPassword.Text = HttpUtility.HtmlEncode(txtNewPassword.Text);
        txtConfirmPassword.Text = HttpUtility.HtmlEncode(txtConfirmPassword.Text);
        txtSecurityCode.Text = HttpUtility.HtmlEncode(txtSecurityCode.Text);

        //OldPassword
        if (rfvOldPassword.Enabled && rfvOldPassword.ValidationGroup == strValidationGroup)
        {
            rfvOldPassword.Validate();
            if (rfvOldPassword.IsValid == false)
            {
                txtOldPassword.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtOldPassword.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtOldPassword.ControlStyle.CssClass = "input-fields";
        }

        //NewPassword
        if (rfvNewPassword.Enabled && rfvNewPassword.ValidationGroup == strValidationGroup)
        {
            rfvNewPassword.Validate();
            if (rfvNewPassword.IsValid == false)
            {
                txtNewPassword.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtNewPassword.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtNewPassword.ControlStyle.CssClass = "input-fields";
        }

        //ConfirmPassword
        if (rfvConfirmPassword.Enabled && rfvConfirmPassword.ValidationGroup == strValidationGroup)
        {
            rfvConfirmPassword.Validate();
            if (rfvConfirmPassword.IsValid == false)
            {
                txtConfirmPassword.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtConfirmPassword.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtConfirmPassword.ControlStyle.CssClass = "input-fields";
        }

        //SecurityCheck
        if (rfvSecurityCheck.Enabled && rfvSecurityCheck.ValidationGroup == strValidationGroup)
        {
            rfvSecurityCheck.Validate();
            if (rfvSecurityCheck.IsValid == false)
            {
                txtSecurityCode.ControlStyle.CssClass = "input-fields validationError";
            }
            else
            {
                txtSecurityCode.ControlStyle.CssClass = "input-fields";
            }
        }
        else
        {
            txtSecurityCode.ControlStyle.CssClass = "input-fields";
        }

    }

}
